import styles from './index.module.less'
import Button from '@/components/button'
import { useSetState } from 'ahooks'
import cm from 'classnames'
import { isValidatePhone } from '@/utils/utils'
import { pick, debounce } from 'lodash-es'
import { addUserAccount } from '@/api/user'
import Toast from '@/components/toast'

const Index = (props) => {
  const { className, addAccount, onClose } = props
  const [formInfo, setFormInfo] = useSetState({})

  const submit = async () => {
    if (!isValidatePhone(formInfo.account)) {
      setFormInfo({ phoneErr: true })
      return
    } else if (!formInfo.realName) {
      setFormInfo({ nameErr: true, phoneErr: false })
    } else {
      const res = await addUserAccount(pick(formInfo, ['account', 'realName']))
      if (!res.code) {
        Toast.normal('收款账户添加成功')
        addAccount({ id: new Date().valueOf(), ...pick(formInfo, ['account', 'realName']) })
        onClose()
      }
    }
  }

  const debounceSubmit = debounce(submit, 300)
  return (
    <div className={cm(styles.addBox, className)}>
      <div className={styles.title}>
        <img src="/images/alipay.png" alt="" />
        <span>支付宝</span>
      </div>
      <img src="/images/close.webp" className={styles.close} alt="" onClick={onClose} />
      <div className={styles.formItem}>
        <span className={styles.formLabel}>支付宝账号：</span>
        <input
          className="input"
          placeholder="请输入支付宝账号或手机号"
          maxLength={20}
          onInput={(e) => setFormInfo({ account: e.currentTarget.value })}
        />
      </div>
      <div className={styles.formItem}>
        <span className={styles.formLabel}>收款人姓名：</span>
        <input
          className="input"
          placeholder="请输入支付宝绑定的收款人姓名"
          maxLength={100}
          onInput={(e) => setFormInfo({ realName: e.currentTarget.value })}
        />
      </div>
      {formInfo.phoneErr && <p className="text-xs leading-3 text-red text-center ">请输入正确的支付宝账号或者手机号</p>}
      {formInfo.nameErr && <p className="text-xs leading-3 text-red text-center ">请输入收款人姓名</p>}
      <Button className={styles.submit} onClick={debounceSubmit}>
        确认
      </Button>
    </div>
  )
}

export default Index
